package com.shizhi.usp.util;

import java.util.zip.CRC32;

/**
 * Time: 2019/11/25 11:36
 * Author: hyh
 * Description:数据包测试完整性工具类
 * start  data...  crc32   end
 * 0xFA    n        1      oxFB
 */
public class PacketTestHelper {

    private static CRC32 crc32 = new CRC32();

    public static byte[] make(byte[] data) {
        synchronized (PacketTestHelper.class) {
            byte[] sendData = new byte[data.length + 3];
            int allLen = sendData.length;
            sendData[0] = (byte) 0XFA;
            System.arraycopy(data, 0, sendData, 1, data.length);
            crc32.reset();
            crc32.update(sendData, 0, allLen - 2);
            sendData[allLen - 2] = (byte) crc32.getValue();
            sendData[allLen - 1] = (byte) 0XFB;
            return sendData;
        }
    }

    public static int[] parse(byte[] recvData, int off, int len) {
        synchronized (PacketTestHelper.class) {
            int indexStart = -1;
            int indexEnd = -1;

            for (int i = off; i < len; i++) {
                if ((byte) 0xFA == recvData[i]) {
                    indexStart = i;
                }
                if (indexStart != -1 && (byte) 0xFB == recvData[i]) {
                    indexEnd = i;
                }
                byte[] checkData = new byte[indexEnd - 2 - indexStart + 1];
                System.arraycopy(recvData, indexStart, checkData, 0, checkData.length);
                crc32.reset();
                crc32.update(checkData);
                if ((byte) crc32.getValue() == recvData[indexEnd - 1]) {
                    return new int[]{indexStart, indexEnd};
                }
            }
            return null;
        }
    }
}
